<template>
  <div class="container">
    <div class="wrapper">
      <div style="font-weight: bold; font-size: 24px; text-align: center; margin-bottom: 30px; color: #1450aa">欢 迎 登 录
      </div>
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" size="large" v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" size="large" v-model="form.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" style="width: 100%" @click="handleLogin">登 录</el-button>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        没有账号？ <router-link to="/register">去注册</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { login, getUserInfo } from "@/api/login";

export default {
  data() {
    return {
      form: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      }
    }
  },
  methods: {
    async handleLogin() {
      try {
        // 1. 表单验证
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;


        // 2. 调用登录接口
        const loginRes = await login(this.form);
        if (loginRes.code !== 200) {
          this.$message.error(loginRes.msg || "登录失败");
          return;
        }

        this.$message.success(loginRes.message || "登录成功");

        // 3. 保存 token
        this.$store.commit('SET_TOKEN', loginRes.data)

        // 4. 获取用户信息
        const userRes = await getUserInfo(this.form.username);
        if (userRes.code === 200) {
          this.$store.commit('SET_USER', userRes.data)
        } else {
          this.$message.warning('获取用户信息失败');
        }

        // 5. 跳转到目标页面
        this.$router.push('/admin');

      } catch (error) {
        console.error('登录失败:', error);
        this.$message.error(error.message || '登录失败，请重试');
      }
    }
  }
}
</script>

<style scoped>
.container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to top, #7f7fd5, #86a8e7, #91eae4);
  background-size: cover;
}

.wrapper {
  width: 350px;
  padding: 50px 30px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .1);
  background-color: rgba(255, 255, 255, .5);
}
</style>